import os
import subprocess
import sys
import threading
import os
from time import sleep

"""资源关系智能问答系统启动脚本"""

# 检查Python版本
if sys.version_info < (3, 8):
    print("错误: 本系统需要Python 3.8或更高版本。")
    sys.exit(1)

def install_dependencies():
    """安装项目依赖"""
    print("正在安装项目依赖...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
        print("依赖安装成功！")
    except subprocess.CalledProcessError as e:
        print(f"依赖安装失败: {e}")
        sys.exit(1)

def read_output(stream, prefix):
    """读取子进程输出的线程函数"""
    try:
        while True:
            line = stream.readline()
            if line:
                print(f"{prefix}: {line.strip()}")
            else:
                break
    except Exception as e:
        print(f"读取输出时出错: {e}")

def run_flask_app():
    """运行Flask应用"""
    print("正在启动Flask应用...")
    
    # 设置环境变量
    os.environ['FLASK_ENV'] = 'development'
    os.environ['FLASK_DEBUG'] = 'True'
    
    try:
        # 直接运行app.py文件，避免相对导入问题
        flask_process = subprocess.Popen(
            [sys.executable, "backend/app.py"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            bufsize=1  # 行缓冲
        )
        
        # 创建线程分别读取标准输出和标准错误
        stdout_thread = threading.Thread(target=read_output, args=(flask_process.stdout, "OUT"))
        stderr_thread = threading.Thread(target=read_output, args=(flask_process.stderr, "ERROR"))
        
        stdout_thread.daemon = True
        stderr_thread.daemon = True
        
        stdout_thread.start()
        stderr_thread.start()
        
        print("应用启动成功！请访问 http://localhost:5000")
        print("按Ctrl+C停止应用...")
        
        # 保持主线程运行，直到收到中断信号
        try:
            while flask_process.poll() is None:
                sleep(0.5)
            
            # 如果应用意外退出，显示退出码
            exit_code = flask_process.returncode
            print(f"\n应用意外退出，退出码: {exit_code}")
            
        except KeyboardInterrupt:
            print("\n正在停止应用...")
            flask_process.terminate()
            try:
                # 等待进程结束，最多等待5秒
                flask_process.wait(timeout=5)
                print("应用已停止。")
            except subprocess.TimeoutExpired:
                # 如果超时，强制终止进程
                print("应用终止超时，强制关闭...")
                flask_process.kill()
                print("应用已强制关闭。")
    except Exception as e:
        print(f"应用启动失败: {e}")
        sys.exit(1)

def main():
    """主函数"""
    print("===== 资源关系智能问答系统 ======")
    
    # 检查.env文件
    if not os.path.exists('.env'):
        print("警告: 未找到.env配置文件。请确保已配置数据库连接和API密钥。")
        input("按Enter键继续...")
    else:
        # 简单检查.env文件内容是否有效
        with open('.env', 'r', encoding='utf-8') as f:
            content = f.read()
            if 'DB_HOST' not in content or 'TONGYI_API_KEY' not in content:
                print("警告: .env文件可能缺少必要的配置项。")
                input("按Enter键继续...")
    
    # 询问是否安装依赖
    install_choice = input("是否需要安装项目依赖？(y/n): ").strip().lower()
    if install_choice == 'y':
        install_dependencies()
    
    # 启动应用
    run_flask_app()

if __name__ == '__main__':
    main()